import time
from flask import Blueprint, jsonify, request
from models import Task, User, DoTask
from exts import db
import code_constant

bp = Blueprint("task", __name__, url_prefix="/task")

@bp.route("/send", methods=["POST", "GET"])
def send():
    # 获取前端发送过来的任务信息
    task_data = request.get_json()
    # task_data = {'tasktitle': 'react', 'taskintro': '做公司官网', 'typeid': '1', 'bounty': 100, 'enddate': '2022-03-26', 'email': '143@qq.com', 'username': '616010445', 'isLogin': True}
    # 先判断用户是否已登录
    if task_data["isLogin"]:
        # 通过提交的email，来判断username是否正确
        if task_data["email"] != None:
            user = User.query.filter_by(email=task_data["email"]).first()
            if user.username == task_data["username"]:
                if user.money >= task_data["bounty"]:
                    task_to_mysql_data = Task(
                        tasktitle = task_data["tasktitle"],
                        taskintro = task_data["taskintro"],
                        createtime = time.time(),
                        enddate = task_data["enddate"], # 暂时存字符串，用于展示，其他版本会对本数据进行其他操作
                        audit = 0, # 默认为待审核
                        typeid = task_data["typeid"],
                        userid = user.id,
                        bounty = task_data["bounty"]
                    )
                    db.session.add(task_to_mysql_data)
                    # 数据插入成功后，得减去用户账户上的原本金额
                    now_money = user.money - task_data["bounty"]
                    user.money = now_money
                    db.session.commit()
                    return jsonify(
                        {
                            "msg": "success",
                            "money": user.money
                        }
                    )
                else:
                    return "您的帐户金币不足", code_constant.user_login_out
            else:
                return "验证不通过", code_constant.user_login_out
    else:
        return "用户没登录", code_constant.user_login_out

# 获取猎人用户的任务统计，数据面板
@bp.route("/worker_task_data_tem", methods=["POST", "GET"])
def worker_task_data_tem():
    params = request.get_json() # {'email': '143@qq.com', 'username': '616010445'}
    user_item = User.query.filter_by(email = params["email"]).first()
    if user_item.username != params["username"]:
        return "no user", 400
    do_tasks = DoTask.query.filter_by(worker_id = user_item.id).all()
    completed_num = 0
    dev_num = 0
    no_start = 0
    for do_task in do_tasks:
        if do_task.task_res == 2:
            completed_num += 1
        elif do_task.task_res == 1:
            dev_num += 1
        elif do_task.task_res == 0:
            no_start += 1
    obj = {
        "completed_num": completed_num,
        "dev_num": dev_num,
        "no_start": no_start
    }
    return jsonify(obj)

# 获取雇主用户的任务统计，数据面板
@bp.route("/master_task_data_tem", methods=["POST", "GET"])
def master_task_data_tem():
    params = request.get_json() # {'email': '143@qq.com', 'username': '616010445'}
    # params = {'email': '143@qq.com', 'username': '616010445'}
    user_item = User.query.filter_by(email = params["email"]).first()
    if user_item.username != params["username"]:
        return "no user", 400
    
    tasks = user_item.task

    audit_pass = 0 # 审核通过
    audit_no_start = 0 # 待审核
    audit_not_pass = 0 # 审核不通过
    completed_num = 0 # 已完成数量
    dev_num = 0 # 开发中数量
    no_start = 0 # 未开始

    for task in tasks:
        if task.audit == 1:
            audit_pass += 1
            if task.taken == 1:
                do_task = task.do_task[0]
                if do_task.task_res == 2:
                    completed_num += 1
                elif do_task.task_res == 1:
                    dev_num += 1
                elif no_start == 0:
                    no_start += 1
            elif task.taken == 0:
                no_start += 1
        elif task.audit == 0:
            audit_no_start += 1
        elif task.audit == 2:
            audit_not_pass += 1

    obj = {
        "audit_pass": audit_pass,
        "audit_no_start": audit_no_start,
        "audit_not_pass": audit_not_pass,
        "completed_num": completed_num,
        "dev_num": dev_num,
        "no_start": no_start
    }
    return jsonify(obj)
    
# 用户修改基本信息
@bp.route("/update_user_info", methods=["POST", "GET"])
def update_user_info():
    params = request.get_json()
    """
    {
        'email': '143@qq.com', 
        'nickname': '鸣人', 
        'intro': '来自facebook的大神，会牛逼的golang和python', 
        'gender': '男', 
        'username': '616010445', 
        'oldEmail': '143@qq.com'
    }
    """
    user_item = User.query.filter_by(username = params["username"]).first()
    if user_item is None:
        return jsonify({"status": 400, "msg": "params error"})
    if user_item.email != params["oldEmail"]:
        return jsonify({"status": 400, "msg": "params error"})

    user_item.email = params["email"]
    user_item.nickname = params["nickname"]
    user_item.userintro = params["userintro"]
    user_item.gender = params["gender"]
    db.session.commit()
    obj = {
        "email": user_item.email,
        "nickname": user_item.nickname,
        "userintro": user_item.userintro,
        "gender": user_item.gender
    }
    return jsonify({"status": 200, "obj": obj})

# 用户修改密码
@bp.route("/update_user_passwd", methods=["POST", "GET"])
def update_user_passwd():
    params = request.get_json() # {'oldPasswd': '1', 'password': '22', 'confirm': '22', 'email': '12306@qq.com', 'username': '616010445'}
    user_item = User.query.filter_by(username = params["username"]).first()
    if user_item is None:
        return jsonify({"status": 400, "msg": "params error"})
    if user_item.email != params["email"]:
        return jsonify({"status": 400, "msg": "params error"})
    
    if user_item.password != params["oldPasswd"]:
        return jsonify({"status": 4000, "msg": "password is no correct"})
    if user_item.password == params["password"]:
        return jsonify({"status": 4001, "msg": "password is save"})
    
    user_item.password = params["password"]
    db.session.commit()
    return jsonify({"status": 200, "msg": "success"})